package com.suep.file.util;

import org.apache.commons.io.FilenameUtils;
import org.springframework.http.MediaType;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

public class FileUtil {
    /**
     * 清理文件名防止路径遍历攻击
     * @return 安全的纯文件名（无路径信息）
     */
    public static String sanitizeFileName(String originalFileName) {
        if (originalFileName == null || originalFileName.isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        return FilenameUtils.getName(originalFileName)
                .replaceAll("[^a-zA-Z0-9.\\-]", "_"); // 替换特殊字符
    }


    // 生成唯一文件名
    public static String generateUniqueFileName(String originalFileName) {
        //末尾保留原有文件名
        String sanitized = sanitizeFileName(originalFileName);
//        String uuid = UUID.randomUUID().toString().substring(0, 8);
        String timestamp = LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        return String.format("%s_%s",
                timestamp, sanitized);
    }
    
    // 根据文件名识别媒体类型
    public static String determineContentType(String fileName) {
        String extension = FilenameUtils.getExtension(fileName).toLowerCase();
        switch (extension) {
            case "jpg":
                return "image/jpg";
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "webp":
                return "image/webp";
            default:
                return MediaType.APPLICATION_OCTET_STREAM_VALUE; // 未知类型
        }
    }
}